<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>定位管理后台 - PHP版本</title>
    <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container { max-width: 1400px; margin: 0 auto; }
        .header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .header h1 { color: #667eea; font-size: 32px; margin-bottom: 10px; }
        .status {
            display: inline-block;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }
        .status.connected { background: #10b981; color: white; }
        .status.disconnected { background: #ef4444; color: white; }
        .main-content { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .card h2 {
            color: #333;
            font-size: 24px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 3px solid #667eea;
        }
        .device-list { display: flex; flex-direction: column; gap: 15px; }
        .device-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border-left: 4px solid #667eea;
        }
        .device-name { font-size: 18px; font-weight: 600; color: #333; }
        .device-id { font-size: 12px; color: #666; font-family: monospace; }
        .location-info {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-top: 10px;
        }
        .location-coords {
            font-family: monospace;
            font-size: 14px;
            color: #667eea;
            margin-bottom: 8px;
        }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            margin-right: 10px;
            background: #667eea;
            color: white;
        }
        .btn:hover { background: #5568d3; }
        .log-container {
            max-height: 400px;
            overflow-y: auto;
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            font-family: monospace;
            font-size: 13px;
        }
        .log-entry {
            padding: 8px;
            margin-bottom: 5px;
            border-left: 3px solid #667eea;
            padding-left: 12px;
        }
        .warning {
            background: #fff3cd;
            border: 1px solid #ffc107;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            color: #856404;
        }
        .empty-state { text-align: center; padding: 40px; color: #999; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📍 定位管理后台 (PHP版本)</h1>
            <p>实时监控和管理设备位置</p>
            <div style="margin-top: 15px;">
                <span id="connection-status" class="status disconnected">API模式</span>
                <span style="margin-left: 15px; color: #666;">设备数: <strong id="device-count">0</strong></span>
            </div>
        </div>
        
        <div class="warning">
            <strong>⚠️ 注意：</strong> PHP版本使用HTTP轮询模式，实时性较Python版本略低。
            如需完整WebSocket实时功能，请确保运行 <code>php server.php</code>
        </div>
        
        <div class="main-content">
            <div class="card">
                <h2>📱 设备列表</h2>
                <div id="device-list" class="device-list">
                    <div class="empty-state">
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
            
            <div class="card">
                <h2>📋 操作日志</h2>
                <div id="log-container" class="log-container"></div>
            </div>
        </div>
    </div>

    <script>
        const logs = [];
        let devices = {};
        
        function addLog(message, type = 'info') {
            const now = new Date();
            const timeStr = now.toLocaleTimeString('zh-CN');
            logs.unshift({ time: timeStr, message, type });
            if (logs.length > 50) logs.pop();
            updateLogDisplay();
        }
        
        function updateLogDisplay() {
            const container = document.getElementById('log-container');
            container.innerHTML = logs.map(log => `
                <div class="log-entry ${log.type}">
                    <span style="color: #666;">${log.time}</span> ${log.message}
                </div>
            `).join('');
        }
        
        function updateDeviceList() {
            const container = document.getElementById('device-list');
            const deviceArray = Object.values(devices);
            
            document.getElementById('device-count').textContent = deviceArray.length;
            
            if (deviceArray.length === 0) {
                container.innerHTML = '<div class="empty-state"><p>暂无设备数据</p></div>';
                return;
            }
            
            container.innerHTML = deviceArray.map(device => {
                // 兼容 last_location 和 location 两种字段名
                const location = device.last_location || device.location;
                const hasLocation = location && location.latitude && location.longitude;
                
                // 格式化最后在线时间
                const lastSeen = device.last_seen || '';
                const statusColor = device.status === 'online' ? '#10b981' : '#6b7280';
                
                return `
                    <div class="device-item">
                        <div class="device-name">${device.device_name || '未知设备'}</div>
                        <div class="device-id">ID: ${device.device_id}</div>
                        ${lastSeen ? `<div class="device-id" style="color: ${statusColor};">⏱️ 最后在线: ${lastSeen}</div>` : ''}
                        
                        ${hasLocation ? `
                            <div class="location-info">
                                <div class="location-coords">
                                    📍 ${location.latitude.toFixed(6)}, ${location.longitude.toFixed(6)}
                                </div>
                                ${location.address ? `<div>📍 ${location.address}</div>` : ''}
                                ${location.location_name ? `<div>🏢 ${location.location_name}</div>` : ''}
                                ${location.accuracy ? `<div>🎯 精度: ${location.accuracy}米</div>` : ''}
                                ${location.is_simulated !== undefined ? `<div>${location.is_simulated ? '🔷 模拟位置' : '🌐 真实位置'}</div>` : ''}
                                ${location.timestamp || location.received_at ? `<div>⏰ 最新上报: ${location.timestamp || location.received_at}</div>` : ''}
                            </div>
                        ` : '<div class="location-info">⚠️ 暂无位置信息</div>'}
                        
                        <div style="margin-top: 10px;">
                            <button class="btn" onclick="requestLocation('${device.device_id}')">
                                📡 请求定位
                            </button>
                            <button class="btn" onclick="viewHistory('${device.device_id}')" style="background: #10b981;">
                                📊 查看历史
                            </button>
                        </div>
                    </div>
                `;
            }).join('');
        }
        
        function requestLocation(deviceId) {
            addLog(`向设备发送定位请求: ${deviceId}`, 'info');
        }
        
        async function viewHistory(deviceId) {
            try {
                const response = await fetch(`api.php/api/device/${deviceId}/history`);
                const data = await response.json();
                
                if (data.history && data.history.length > 0) {
                    const historyHtml = data.history.slice(-10).reverse().map(loc => `
                        <div style="padding: 10px; background: #f8f9fa; margin-bottom: 8px; border-radius: 5px;">
                            <div>📍 ${loc.latitude.toFixed(6)}, ${loc.longitude.toFixed(6)}</div>
                            <div style="font-size: 12px; color: #666;">
                                ${loc.address || '无地址信息'}<br>
                                精度: ${loc.accuracy}米 | ${loc.is_simulated ? '模拟' : '真实'}<br>
                                时间: ${loc.timestamp || loc.received_at}
                            </div>
                        </div>
                    `).join('');
                    
                    alert(`最近10条位置记录:\n\n${data.history.length}条历史记录`);
                    // 可以改成弹窗显示
                    const modal = document.createElement('div');
                    modal.innerHTML = `
                        <div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 1000; display: flex; align-items: center; justify-content: center;" onclick="this.remove()">
                            <div style="background: white; padding: 30px; border-radius: 15px; max-width: 600px; max-height: 80vh; overflow-y: auto;" onclick="event.stopPropagation()">
                                <h3 style="margin-bottom: 20px;">位置历史 (最近10条)</h3>
                                ${historyHtml}
                                <button class="btn" onclick="this.closest('div[style*=fixed]').remove()" style="margin-top: 15px; width: 100%;">关闭</button>
                            </div>
                        </div>
                    `;
                    document.body.appendChild(modal);
                } else {
                    alert('暂无历史记录');
                }
            } catch (error) {
                console.error('获取历史失败:', error);
                alert('获取历史记录失败');
            }
        }
        
        function loadDevices() {
            // 添加时间戳参数防止缓存
            const timestamp = new Date().getTime();
            fetch(`api.php/api/devices?_t=${timestamp}`, {
                cache: 'no-cache',  // 禁用缓存
                headers: {
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0'
                }
            })
                .then(res => res.json())
                .then(data => {
                    if (data.devices) {
                        devices = {};
                        data.devices.forEach(device => {
                            devices[device.device_id] = device;
                        });
                        updateDeviceList();
                        addLog(`已加载 ${data.devices.length} 个设备`, 'info');
                    }
                })
                .catch(err => {
                    addLog('加载设备列表失败: ' + err.message, 'error');
                });
        }
        
        // 初始加载
        addLog('管理后台已启动 (PHP版本)', 'info');
        loadDevices();
        
        // 每5秒自动刷新设备列表
        setInterval(() => {
            loadDevices();
        }, 5000);
        
        addLog('已启用自动刷新 (每5秒)', 'info');
    </script>
</body>
</html>

